package com.zimug.courses.security.basic.auth.service;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: liull
 * @Description:
 * @Date: Created in 22:57 2020/11/25
 * @Modified By:
 */
@Component("rbacService")
public class RbacService {
    /**
     * 判断是否有访问资源的权限
     * 
     * @param authentication 认证信息
     * @param request 请求信息
     * @return
     */
    public boolean hasPermission(Authentication authentication, HttpServletRequest request) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) principal;
            // 获取用户的权限列表
            // 获取请求的url信息
            String uri = request.getRequestURI();
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(uri);
            return userDetails.getAuthorities().contains(simpleGrantedAuthority);
        }
        return false;
    }
}
